package socket

import (
	"fmt"
	"game/readygo/handler"
	skt "game/readygo/socket"
	"tcs-server/tcs-game-server/src/foundation/player"
	"tcs-server/tcs-protobuf/src/tcsprotobuf"

	"google.golang.org/protobuf/proto"
)

// implement ConnectHandler
type SocketHandler struct {
}

const (
	PLAYERCONTEXT string = "PLAYERCONTEXT"
)

func (this *SocketHandler) ConnectActive(connCtx *skt.ConnectContext) (err error) {
	var playerContext player.PlayerContext
	playerContext.SetConnect(connCtx)
	connCtx.PutAttr(PLAYERCONTEXT, &playerContext)
	return
}

func (this *SocketHandler) ConnectInactive(connCtx *skt.ConnectContext) (err error) {
	return
}

func (this *SocketHandler) ConnectRead(connCtx *skt.ConnectContext, in []byte) (err error) {
	var wrapper tcsprotobuf.MessageWrapper
	proto.Unmarshal(in, &wrapper)

	cmdInvoker := handler.GetHandler(int(wrapper.ProtoId))
	playerContext := connCtx.GetAttr(PLAYERCONTEXT).(*player.PlayerContext)
	if cmdInvoker != nil {
		var playerCmdMessage player.PlayerCmdMessage
		playerCmdMessage.PlayerContext = playerContext
		playerCmdMessage.Wrapper = &wrapper
		cmdInvoker.Invoke(&playerCmdMessage)
	} else {
		fmt.Printf("未找到协议编号【%v】的处理器\n", wrapper.ProtoId)
	}
	return
}

func (this *SocketHandler) ErrorCatch(connCtx *skt.ConnectContext, cause error) (err error) {
	return
}
